package cn.com.code.generator.service.impl;

import cn.com.code.generator.entity.User;
import cn.com.code.generator.service.UserService;
import cn.com.code.generator.thread.ThreadExecution;
import cn.com.code.generator.utils.BaseUtil;
import cn.com.do1.dsf.common.exception.RestException;
import cn.com.do1.dsf.common.utils.SpringContextUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class BatchSaveUserThreadExecutionImpl implements ThreadExecution {
    private static final Logger logger = LoggerFactory.getLogger(BatchSaveUserThreadExecutionImpl.class);
    private String name;
    private Map<String, Object> variables;
    private Map<String, List<String>> returnResp;

    private UserService userService;
    public BatchSaveUserThreadExecutionImpl(String name,Map<String, Object> variables,Map<String, List<String>> returnResp){
        this.name = name;
        this.variables = variables;
        this.returnResp = returnResp;
        userService = SpringContextUtils.getBean(UserService.class);
    }

    /**
     * 实现批量保存用户方法
     * 在这里加@Transactional(rollbackFor = Exception.class)没有生效
     * @param sequence
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void executeBatch(List<Integer> sequence) {
        try {
            String threadName = Thread.currentThread().getName();
            Long id = Thread.currentThread().getId();
            logger.info("ThreaName={};ThreadId={}", threadName,id);
            logger.info("variables={}", JSONObject.toJSONString(variables));
            List<User> users = sequence.stream().map(src -> {
                User target = new User();
                target.setId(BaseUtil.getUUID32());
                target.setName(name+src);
                target.setAge(src);
                return target;
            }).collect(Collectors.toList());
            userService.insertBatch(users);
            //事务回滚校验，手动制造异常
            /*if(name.contains("-thread-2")){
                logger.info("error=============");
                int a = 2/0;
            }*/
            List<String> ids = users.stream().map(User::getId).collect(Collectors.toList());
            returnResp.put("ThreadId="+id,ids);
            logger.info("ids={}", JSONObject.toJSONString(ids));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("错误信息="+e.getMessage());
            String name = Thread.currentThread().getName();
            Long id = Thread.currentThread().getId();
            logger.info("ThreaName={};ThreadId={},子线程异常", name,id);
            throw  new RestException("保存用户失败");
        }
    }
}
